package m.permission.controller;
import java.util.List;

import m.framework.controller.BaseController;
import m.framework.controller.Task;
import m.framework.dao.selector.PageRecord;
import m.framework.dao.selector.Query;
import m.framework.enums.FileModule;
import m.framework.enums.FileType;
import m.framework.enums.YesOrNo;
import m.framework.exception.Message;
import m.framework.exception.SystemException;
import m.framework.service.BaseService;
import m.framework.utils.StringUtil;
import m.permission.model.Menu;
import m.permission.model.User;
import m.permission.util.QueryToExcel;
import m.toolkit.excel.ExcelUtil;
import m.toolkit.file.model.FileInfo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;

/**
 * @author ming
 * @date 2014年2月19日下午4:11:20
 */
@Controller
public class FrameController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(FrameController.class);
	public static final int MAX_EXPORT=10000;
	
	@Task("登陆")
	public User login(User user){	
		if(StringUtil.isEmpty(user.getUserCode())){
			throw new Message("请输入用户名");
		}
		if(StringUtil.isEmpty(user.getPwd())){
			throw new Message("请输入密码");
		}
		Query query=Query.forClass(User.class);
		query.eq("userCode", user.getUserCode());
		query.eq("pwd", StringUtil.md5(user.getPwd()));
		List<User> list=BaseService.getDefault().query(query);
		if(list.size()==0){
			throw new Message("用户名或密码不正确");
		}
		user=list.get(0);
		//将用户放入当前线程
		setUser(user);
		return  user;
	}
	
	/**进入首页,显示一级菜单*/
	public List<Menu> index(){
		for(Menu m:Menu.getAll()){
			if(m.getId().equals(Menu.ROOT_ID)){
				return m.getChildren();
			}
		}
		throw new SystemException("找不到系统菜单,请确认文件"+Menu.MENU_FILE+"是否正确");
	}
	
	/**重新加载菜单*/
	public List<Menu> reloadMenu(){
		Menu.reload();
		return index();
	}

	@Task("将查询结果导出到excel")
	public FileInfo toExcel(QueryToExcel excel,PageRecord pageRecord ) {
		pageRecord.setPageNo(1);
		if(pageRecord.getCount()>MAX_EXPORT){
			throw new Message("系统1此最多允许导出"+MAX_EXPORT+"条记录");
		}
		pageRecord.setRowsPerPage(MAX_EXPORT);
		pageRecord=queryContinue(pageRecord);
		
		List list= excel.createExcelContent(pageRecord);
		
		FileInfo file=new FileInfo();
		file.newFile(FileModule.export, FileType.excel);
		file.setOriName(excel.fileName());
		file.setIsExists(YesOrNo.Y);
		ExcelUtil.createExcel(file.getDownLoadPath(), list);
		
		this.defultService().insert(file);
		return file;
	}
}




